package com.eco.fishway.service;

import com.eco.fishway.util.NettyCtxMap;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;

/**
 * @author: xulinyu
 * Created at: 2024/8/7 16:23
 */
@Slf4j
@Service
public class LightService {

    private static final String OFF_COMMAND_LIGHT = "00 00 00 00 00 06 FF 05 00 66 00 00";
    private final StringRedisTemplate stringRedisTemplate;

    public LightService(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void sendCommand(String clientId, String command) {
        try {
            //存储开关状态
            stringRedisTemplate.opsForValue().set(clientId, command.equals(OFF_COMMAND_LIGHT) ? "0" : "1");
            if (StringUtils.isEmpty(clientId) || StringUtils.isEmpty(command)) {
                log.error("clientId or command is null");
                return;
            }
            ChannelHandlerContext ctx = NettyCtxMap.get(clientId);
            if (ctx == null) {
                log.error("ChannelHandlerContext is null");
                return;
            }
            String msg = new String(command.getBytes(), "utf-8");
            log.info("发送的指令：[{}]", msg);
            ctx.writeAndFlush(msg);
            log.info("send command to {} success", clientId);

        } catch (UnsupportedEncodingException e) {
            log.error(e.toString());
        }
    }
}
